package cn.ilikes.tools.nosql.jpa.clients.indexs.index.hadoops;

import java.io.IOException;

import org.apache.lucene.store.Lock;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;

public class HadoopZooKeepLock extends Lock {

	private Logger logger = Loggerfactory.instance(HadoopZooKeepLock.class);
	
	private ZooKeeper zooKeeper;

	private String path;

	private String lockId;

	public HadoopZooKeepLock(ZooKeeper zooKeeper, String path, String lockId) {
		super();
		this.zooKeeper = zooKeeper;
		this.path = path;
		this.lockId = lockId;
	}

	@Override
	public boolean isLocked() throws IOException {
		try {
			boolean result = HadoopZooKeepLockUnilts.isLocked(zooKeeper, path, lockId);
			if(Loggerfactory.isdebug(logger))Loggerfactory.debug(logger, "isLocked  :  "+result);
			return result;
		} catch (Exception e) {
			throw new IOException(e);
		}

	}

	@Override
	public boolean obtain() throws IOException {
		try {
			
			boolean result = HadoopZooKeepLockUnilts.obtainLock(zooKeeper, path, lockId);
			if(Loggerfactory.isdebug(logger))Loggerfactory.debug(logger, "obtain  :  "+result);
			return result;
		} catch (Exception e) {
			throw new IOException(e);
		}
	}

	@Override
	public void release() throws IOException {
		try {
			if(Loggerfactory.isdebug(logger))Loggerfactory.debug(logger, "release  :  ");
			HadoopZooKeepLockUnilts.release(zooKeeper, path,lockId);
		} catch (Exception e) {
			throw new IOException(e);
		}

	}

}
